<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2018/11/17
 * Time: 15:07
 */
namespace app\common\service\swooleJobs;
use app\common\library\CommonFun;
use app\common\model\article\JPushArticleModel;
use app\common\model\article\PublishArticleModel;
use app\common\model\coin\CoinRuntimeModel;
use app\common\model\pair\PairRuntimeModel;
use app\common\model\pushlog\JpushArriveUpSensorsModel;
use app\common\model\user\UserDevicesModel;
use app\common\redis\WeChatPushArticleRepeatRedis;
use app\common\service\ArticlePushTplFormat;
use app\common\service\ElkLog;
use app\common\service\GeTuiService;
use app\common\service\SwooleJob;

class JpushArticleJobs
{
    /**
     * 加入推送队列
     */
    public static function ArticlePushJobs( $id )
    {
        SwooleJob::push( 'MyJob', __CLASS__ ,'ArticlePush', array( $id ) );
    }

    /**
     * 第一次关注币种推送 Python
     */
    public static function firstFollowPushJobs( array $param )
    {
        SwooleJob::push( 'PythonClient', __CLASS__ ,'firstFollowPush', array( $param['user_id'], $param['coin_id'], 0 ) );
    }

    /**
     * CMS自定义推送
     * @param $title
     * @param $body
     * @param $jump
     * @param $coin_id
     */
    public static function CmsCustomPushJobs( $title, $body, $jump, $coin_id_list , $test_user_id_list ){
        SwooleJob::push( 'MyJob', __CLASS__ ,'CmsCustomPush', array( $title, $body, $jump, $coin_id_list , $test_user_id_list ) );
    }

    /**
     * H5关注币种用户第一次推送
     * @param array $param
     * @param int $delay
     */
    public static function firstFollowMqPushJobs( array $param ,$delay = 0 )
    {
        SwooleJob::push_mq( 'RabbitMq', __CLASS__ ,'firstFollowPush', array( $param['user_id'], $param['coin_id'] ), array( "delay" => $delay ) );
    }

    /**
     * 日报异步推送队列
     */
     public static function userPairDailyPushJobs( array $param )
     {
        SwooleJob::push( 'MyJob', __CLASS__ ,'userPairDailyPush', array( $param['user_id_list'], $param['coin_id_list'] ) );
     }

    /**
     * 延时推送
     */
    public static function userPairMarketReportMqJobs( $user_list_by_coin_list , $delay = 0 )
    {
        SwooleJob::push_mq( 'RabbitMq',__CLASS__,'userPairMarketReportMq', array( $user_list_by_coin_list ), array( "delay" => $delay ) );
    }

    /**
     * 加入推送队列
     * @param $user_list_by_coin_list
     */
    public function userPairMarketReportMq( $user_list_by_coin_list )
    {
        ElkLog::write( array( "message"=> "userPairMarketReportMq") );

        foreach ( $user_list_by_coin_list as $key => $value ){
            JpushArticleJobs::userPairMarketReportJobs( array( "user_id_list" => $value['user_id_list'], "coin_id_list" => $value['coin_id_list'] ) );
            echo "设置用户的推送";
            var_dump( $value['user_id_list'] );
        }
    }


    /**
     * 市场报告推送
     */
    public static function userPairMarketReportJobs( array $param )
    {
        SwooleJob::push( 'TimingPush', __CLASS__ ,'userPairMarketReport', array( $param['user_id_list'], $param['coin_id_list'] ) );
    }

    /**
     * 市场报告推送
     */
    public function userPairMarketReport( $user_id_list, array $coin_id_list )
    {
        ElkLog::write( array( 'message'=> 'userPairMarketReport', 'user_id'=> $user_id_list, "coin_id" => $coin_id_list ) );
        $PublishArticleModel = new PublishArticleModel();
        $UserDevicesModel = new UserDevicesModel();
        $where = array(
            "user_id" => array( 'in', $user_id_list ),
        );

        $devises_list = $UserDevicesModel->where( $where )->select();

        $data_list = $this->get_push_list( $devises_list );

        if ( !$data_list['getui_id_list'] ){
            return false;
        }

        $ArticlePushTplFormat = new ArticlePushTplFormat();
        $article_id_list = $ArticlePushTplFormat->market_report( $coin_id_list );

        if ( !$article_id_list ){
            return false;
        }

        foreach ( $article_id_list as $value ){
            $article_info = $PublishArticleModel->get_data_by_id( $value );
            if ( !$article_info ){
                continue;
            }

            $geTui = new GeTuiService();
            $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'] , $article_info['title'], $article_info['summary'], $PublishArticleModel->get_push_jump_url( $article_info['h5_url'] , $article_info['id']) );

            // 记录推送数据
            if( $contentId ){
                $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
                $add['push_msg_id_list'] = $contentId;
                $add['push_count_ios'] = $data_list['ios_count'];
                $add['push_count_android'] = $data_list['android_count'];
                $add['coin_id'] = json_encode( $article_info['coin_list'] );
                $add['article_id'] = $article_info['id'];
                $add['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
                $add['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_24_HOUR_REPORT;
                $add['content'] = CommonFun::json_encode2( $article_info );
                // 添加推送记录
                $JpushArriveUpSensorsModel->add_log( $add, $user_id_list );
            }
        }
        return true;
    }


    /**
     * 日报数据推送
     * @param $user_id_list
     * @param array $coin_id_list
     * @return bool
     */
    public function userPairDailyPush( $user_id_list, array $coin_id_list )
    {
        ElkLog::write( array( 'message'=> 'userPairDailyPush', 'user_id'=> $user_id_list, "coin_id" => $coin_id_list ) );
        $PublishArticleModel = new PublishArticleModel();
        $UserDevicesModel = new UserDevicesModel();
        $where = array(
            "user_id" => array( 'in', $user_id_list ),
        );

        $devises_list = $UserDevicesModel->where( $where )->select();

        $data_list = $this->get_push_list( $devises_list );
        if ( !$data_list['getui_id_list'] ){
            return false;
        }

        $article_id_list = $PublishArticleModel->createDataDailyList( $coin_id_list );
        if ( !$article_id_list ){
            return false;
        }

        foreach ( $article_id_list as $value ){
            $article_info = $PublishArticleModel->get_data_by_id( $value );
            if ( !$article_info ){
                continue;
            }

            $geTui = new GeTuiService();
            $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'] , $article_info['title'], $article_info['summary'], $PublishArticleModel->get_push_jump_url( $article_info['h5_url'], $article_info['id'] ) );

            // 记录推送数据
            if( $contentId ){
                $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
                $update['push_msg_id_list'] = $contentId;
                $update['push_count_ios'] = $data_list['ios_count'];
                $update['push_count_android'] = $data_list['android_count'];
                $update['coin_id'] = json_encode( $article_info['coin_list'] );
                $update['article_id'] = $article_info['id'];
                $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
                $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_DAILY_PUSH;
                $update['content'] = CommonFun::json_encode2( $article_info );
                $JpushArriveUpSensorsModel->add_log( $update ,$user_id_list );
            }
        }

        return true;
    }

    /**
     * 第一次关注币种推送数据日报
     * @param $user_id
     * @param $coin_id
     * @return bool
     */
    public function firstFollowPush( $user_id, $coin_id, $is_android_push = 1 )
    {
        ElkLog::write( array( 'message'=> 'firstFollowPushJobs', '$user_id'=> $user_id, "coin_id" => $coin_id ) );

        // 获取用户推送id
        $UserDevicesModel = new UserDevicesModel();
        $devices = $UserDevicesModel->get_data_by_unique_key( 'user_id', $user_id );

        // 若该用户没有个推标识
        if ( !$devices || empty( $devices['getui'] ) ){
            return false;
        }

        if ( $devices['type'] == 'android' && $is_android_push == 0 ){
            return false;
        }

        // 获取币种
        $coinRuntimeModel = new CoinRuntimeModel();
        $coinInfo = $coinRuntimeModel->get_data_by_id( $coin_id );

        if ( !$coinInfo ){
            return false;
        }

        $publishArticleModel = new PublishArticleModel();
        $article_id = $publishArticleModel->createDataDaily( $coin_id, true );
        $article_info = $publishArticleModel->get_data_by_id( $article_id );

        if ( !$article_id ) {
            ElkLog::write( array( 'message'=> 'firstFollowPushJobsError', '$user_id'=> $user_id, "coin_id" => $coin_id ) );
            return false;
        }


        $geTui = new GeTuiService();
        $contentId = $geTui->pushMessageToList( array( $devices['getui'] ), $article_info['title'], $article_info['summary'], $publishArticleModel->get_push_jump_url( $article_info['h5_url'] , $article_id ) );

        // 记录推送数据
        if( $contentId ){
            $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
            $update['push_msg_id_list'] = $contentId;
            $update['push_count_ios'] = $devices['type'] == "android" ? 0 : 1;
            $update['push_count_android'] = $devices['type'] == "android" ? 1 : 0;
            $update['coin_id'] = $coin_id;
            $update['article_id'] = $article_id;
            $update['push_user_id_list'] = json_encode( array( $devices['getui'] ) );
            $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_FOLLOW_TOKEN;
            $update['content'] = CommonFun::json_encode2( array("数据日报") );
            $JpushArriveUpSensorsModel->add_log( $update , $user_id );
        }

        return true;
    }

    /**
     * 币种价格异动推送
     */
    public static function priceAlarmPushJobs( array $param )
    {
        SwooleJob::push( 'PythonClient', __CLASS__ ,'priceAlarm', array( $param ) );
    }

    /**
     * 交易对价格异动推送
     */
    public static function pairAlarmPushJobs( array $param )
    {
        SwooleJob::push( 'PythonClient', __CLASS__ ,'PairAlarm', array( $param ) );
    }

    /**
     * 价格异动推送
     */
    public function priceAlarm( array $info )
    {
        $userDevicesModel = new UserDevicesModel();                // 获取用户对应的推送id列表
        $user_jpush_list = $userDevicesModel->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $info['uids'] ) ) );

        ElkLog::write( array( "message" => "priceAlarm", "data" => $info ) );

        $data_list = $this->get_push_list( $user_jpush_list );
        if ( !$data_list['getui_id_list'] ){
            return false;
        }

        $geTui = new GeTuiService();
        $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'], $info['title'], $info['body'], $info['jump'],  300 * 1000 );

        // 记录推送数据
        if( $contentId ){
            $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
            $update['push_msg_id_list'] = $contentId;
            $update['push_count_ios'] = $data_list['ios_count'];
            $update['push_count_android'] = $data_list['android_count'];
            $update['coin_id'] = $info['coin_id'];
            $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
            $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_REMIND;
            $update['content'] = CommonFun::json_encode2( $info );
            $JpushArriveUpSensorsModel->add_log( $update, $data_list['user_id_list'] );
        }

        return true;
    }


    /**
     * 上报交易对数据
     */
    public function PairAlarm( $info )
    {
        $userDevicesModel = new UserDevicesModel();                // 获取用户对应的推送id列表
        $user_jpush_list = $userDevicesModel->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $info['uids'] ) ) );

        ElkLog::write( array( "message" => "PairAlarm", "data" => $info ) );

        $data_list = $this->get_push_list( $user_jpush_list );
        if ( !$data_list['getui_id_list'] ){
            return false;
        }

        $geTui = new GeTuiService();
        $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'], $info['title'], $info['body'], $info['jump'], 300 * 1000 );

        // 记录推送数据
        if( $contentId ){
            $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
            $update['push_msg_id_list'] = $contentId;
            $update['push_count_ios'] = $data_list['ios_count'];
            $update['push_count_android'] = $data_list['android_count'];
            $update['coin_id'] = $info['coin_id'];
            $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
            $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_REMIND;
            $update['content'] = CommonFun::json_encode2( $info );
            $JpushArriveUpSensorsModel->add_log( $update, $data_list['user_id_list'] );
        }
        return true;
    }

    /**
     * CMS后台自定义推送
     * @param $title
     * @param $body
     * @param $jump
     * @param array $coin_id_list
     * @param array $test_user_id_list
     * @return bool
     */
    public function CmsCustomPush( $title, $body, $jump, array $coin_id_list , array $test_user_id_list )
    {
        $geTui = new GeTuiService();
        $is_all = 0;

        if ( $coin_id_list || $test_user_id_list ){
            $UserDevicesModel = new UserDevicesModel();
            $pair_runtime = PairRuntimeModel::getInstance();
            $user_id_list = array();

            foreach ( $coin_id_list as $value ){
                $id_list = $pair_runtime->get_user_list_by_coin_id( $value );
                $user_id_list = array_merge( $user_id_list, $id_list );
            }

            $user_id_list = array_unique( $user_id_list );

            $user_id_list = array_values( $user_id_list );

            if ( $test_user_id_list ){
                $user_id_list = $test_user_id_list;
            }

            if ( !$user_id_list ){
                return false;
            }


            // 获取用户对应的推送id列表
            $user_jpush_list = $UserDevicesModel->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $user_id_list ) ) );

            $data_list = $this->get_push_list( $user_jpush_list );

            $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'], $title, $body, $jump );
        } else {
            $data_list = array(
                "getui_id_list" => array(),
                "ios_count"   => 0,
                "android_count"   => 0,
                "user_id_list"    => array()
            );

            $contentId = $geTui->pushMessageToApp( $title, $body, $jump );
            $is_all = 1;
        }

        // 记录推送数据
        if( $contentId ){
            $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
            $update['push_msg_id_list'] = $contentId;
            $update['push_count_ios'] = $data_list['ios_count'];
            $update['push_count_android'] = $data_list['android_count'];
            $update['coin_id'] = json_encode( $coin_id_list );
            $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
            $update['type'] = $JpushArriveUpSensorsModel::CMS_CUSTOM_PUSH;
            $update['content'] = CommonFun::json_encode2( array( $title, $body, $jump, $coin_id_list  ) );
            $JpushArriveUpSensorsModel->add_log( $update, $data_list['user_id_list'], $is_all );
        }

        return true;
    }


    /**
     * @param $id
     * @return bool
     */
    public function ArticlePush ( $id )
    {
        ElkLog::write( array( 'message'=> 'JpushArticleJobs_ArticlePush', 'data'=> array( 'id'=> $id ) ) );
        $pair_runtime = PairRuntimeModel::getInstance();
        $user_devices_model = UserDevicesModel::getInstance();

        $JPushArticleModel = new JPushArticleModel();
        $redisModel = new WeChatPushArticleRepeatRedis();
        $article_info = $JPushArticleModel->get_data_by_id( $id );

        // 若没有推送数据或者推送失效或者未到推送时间则放弃队列推送
        if( !$article_info || $article_info['is_push'] != -1 || strtotime( $article_info['push_time'] ) > time() ){
            return false;
        }

        $data = $JPushArticleModel->fill_push( $article_info );

        // 更新状态为已推送
        $update = array(
            'is_push' => 1,
        );

        $JPushArticleModel->update_data($data['id'], $update);

        if ( $data['coin_id'] != 0 ){
            // 获取推送币种下用户列表
            if ( $data['coin_id'] > 0 ){
                $user_id_list = $pair_runtime->get_user_list_by_coin_id( $data['coin_id'] );
                if ( !$user_id_list ){
                    return false;
                }

                $user_id_list = array_values( $user_id_list );

                // 获取用户对应的推送id列表
                $user_jpush_list = $user_devices_model->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $user_id_list ) ) );

                if ( ! $user_jpush_list ){
                    return false;
                }

            } else {
                $user_jpush_list = $JPushArticleModel->get_not_follow_coin_getui_list();
            }


            $data_list = $this->get_push_list( $user_jpush_list );
            $getui_id_list = array();

            foreach ( $data_list['getui_id_list'] as $key => $value ){
                if ( !$value ){
                    continue;
                }

                // 增加文章推送缓存
                if ( !$redisModel->Setnx( 1,$redisModel->getRedisKey( $value, $data['article_id']) ) ){
                    // 检测3分钟内有推送
                    continue;
                }

                $redisModel->Expire( 180,$redisModel->getRedisKey( $value, $data['article_id'] ) );

                $getui_id_list[] = $value;
            }

            $data_list['getui_id_list'] = $getui_id_list;
            
        } else {
            $data_list = array(
                "getui_id_list" => array(),
                "ios_count"   => 0,
                "android_count"   => 0,
                "user_id_list"    => array()
            );
        }

        // 若没有推送列表则退出
        if ( !$data_list['getui_id_list'] && $data['coin_id'] != 0 ){
            return false;
        }
        ElkLog::write( array( 'message'=> 'JpushArticleJobs_ArticlePush', 'data'=> array( 'id'=> $id ) , "data2" => "test2") );
        $contentId = $this->push( $data, $data_list['getui_id_list'] );
        ElkLog::write( array( 'message'=> 'JpushArticleJobs_ArticlePush', 'data'=> array( 'id'=> $id ) , "data2" => "test3") );
        if ( $contentId ){
            $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
            $update['push_msg_id_list'] = $contentId;
            $update['push_count_ios'] = $data_list['ios_count'];
            $update['push_count_android'] = $data_list['android_count'];
            $update['coin_id'] = $data['coin_id'];
            $update['article_id'] = $data['article_id'];
            $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
            $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_ARTICLE;
            $update['content'] = CommonFun::json_encode2( $data );

            $JpushArriveUpSensorsModel->add_log( $update, $data_list['user_id_list'] , $data['coin_id'] == 0 ? 1 : 0 );
        }

        return true;
    }

    /**
     * 获取推送数据
     */
    public function get_push_list( $list )
    {
        $ios_count = 0;
        $android_count = 0;
        $getui_id_list = array();
        $user_id_list = array();

        foreach ( $list as $value ) {
            if ( !$value['getui'] ){
                continue;
            }

            if ( $value['getui'] ){
                $getui_id_list[] = $value['getui'];
                if ( $value['type'] == 'ios' ){
                    $ios_count ++;
                } else {
                    $android_count ++;
                }
            }

            if ( $value['user_id'] ){
                $user_id_list[] = $value['user_id'];
            }

        }

        $data = array(
            "getui_id_list" => $getui_id_list,
            "ios_count"     => $ios_count,
            "android_count"  => $android_count,
            "user_id_list"   => $user_id_list
        );

        return $data;
    }

    /**
     * 推送
     */
    public function push( $push_data, $getui_id_list )
    {
        $geTui = new GeTuiService();

        if (  $push_data['coin_id'] != 0 ) {
            if ( $push_data['coin_id'] > 0 ){
                $contentId = $geTui->pushMessageToList( $getui_id_list, $push_data['symbol'].' 最新资讯', "【{$push_data['title']}】{$push_data['summary']}", $push_data['jump'] );
            } else {
                $contentId = $geTui->pushMessageToList( $getui_id_list, $push_data['article_type'] == PublishArticleModel::CMS_TYPE_ARTICLE ? $push_data['title'] : "快讯" , $push_data['article_type'] == PublishArticleModel::CMS_TYPE_ARTICLE ? $push_data['summary'] :"【{$push_data['title']}】{$push_data['summary']}", $push_data['jump'] );
            }

        } else {
            $contentId = $geTui->pushMessageToApp( $push_data['article_type'] == PublishArticleModel::CMS_TYPE_ARTICLE ? $push_data['title'] : "快讯" , $push_data['article_type'] == PublishArticleModel::CMS_TYPE_ARTICLE ? $push_data['summary'] :"【{$push_data['title']}】{$push_data['summary']}", $push_data['jump'] );
        }

        return $contentId;
    }


}